﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace windows_turn_off_screen {
  public partial class Form1 : Form {
    public Form1(bool aLock) {
      if (aLock) {
        //锁屏+关屏
        LockWorkStation();
        SendMessage(this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2);
      } else {
        //禁止鼠标键盘动作+关屏
        BlockInput(true);
        SendMessage(this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2);
        BlockInput(false);
        BlockInput(true);
      }
      this.Close();
      Environment.Exit(0);
    }

    private void Form1_Load(object sender, EventArgs e) {

    }

    //关屏
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    //禁止鼠标键盘动作
    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern bool BlockInput([In, MarshalAs(UnmanagedType.Bool)] bool fBlockIt);
    //锁屏
    [DllImport("user32.dll")]
    public static extern bool LockWorkStation();

  }
}
